package com.zaofan.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zaofan.bean.Goods;
import com.zaofan.bean.GoodsType;
import com.zaofan.constant.StateConstant;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.GoodsDao;
import com.zaofan.exception.ServiceException;

public class GoodsService {
	private GoodsDao goodsDao = new GoodsDao();
	private GoodsTypeService typeService = new GoodsTypeService();

	public void delete(Goods goods) {
		goodsDao.del(goods);
	}

	public void add(Goods goods) throws ServiceException {
		goods.setAddTime(new Date());
		GoodsType type = typeService.findById(goods.getType());
		if (type == null) {
			throw new ServiceException("请设置产品类别");
		}
		goods.setTypeName(type.getName());
		goods.setDateCount(0);
		goods.setPraise(0);
		goods.setState(0);
		goodsDao.add(goods);
	}

	public void update(Goods goods) throws ServiceException {
		goods.setUpdateTime(new Date());
		GoodsType type = typeService.findById(goods.getType());
		if (type == null) {
			throw new ServiceException("请设置产品类别");
		}
		goods.setTypeName(type.getName());
		goodsDao.update(goods);
	}

	public List<Goods> findAll(Map<String, Object> params) {
		List<Goods> data = goodsDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public List<Goods> findByType(int type) throws ServiceException {
		GoodsType goodsType = typeService.findById(type);
		if (goodsType == null) {
			throw new ServiceException("产品类别信息有误");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("type", type);
		List<Goods> data = goodsDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return goodsDao.count(params);
	}

	public Goods findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return goodsDao.findOne(params);
	}

	public void setGoodsState(Goods goods) {
		goodsDao.setGoodsState(goods);
	}

	public void updateDateSellCount() {
		goodsDao.updateDateSellCount();
	}

	public List<Goods> findByTypeWithPage(int type, int begin, int end) throws ServiceException {
		GoodsType goodsType = typeService.findById(type);
		if (goodsType == null) {
			throw new ServiceException("产品类别信息有误");
		}
		Map<String, Object> params = new HashMap<>();
		params.put("type", type);
		params.put("begin", begin + "");
		params.put("end", end + "");
		params.put("state", StateConstant.STATE_SHOW);
		params.put("order", " by sort desc");
		List<Goods> data = goodsDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		for (Goods goods : data) {
			goods.setImage(UrlConstant.HOST_URL + goods.getImage());
			goods.setBigImage(UrlConstant.HOST_URL + goods.getBigImage());
		}
		return data;
	}

}
